﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;

namespace FangChanCrm
{
    public static class Helper
    {
        public static string ListToJsonAddFenYe<T>(IList<T> list, int start, int limit)
        {
            var RetList = list.Skip(start).Take(limit).ToList();
            string returnjson = JsonConvert.SerializeObject(RetList, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
            string jsonString = "{\"draw\":1,\"total\":" + list.Count + ",\"total\":" + list.Count + ",";
            jsonString += "\"" + "data" + "\":" + "" + returnjson + "" + ",";
            jsonString = jsonString.TrimEnd(',');
            jsonString += "}";
            return jsonString;
        }
        public static string ListToJsonAddFenYeHYYSuperFast<T>(IList<T> list, int allcount)
        {
            string returnjson = JsonConvert.SerializeObject(list, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore });
            string jsonString = "{\"draw\":1,\"total\":" + allcount + ",\"total\":" + allcount + ",";
            jsonString += "\"" + "data" + "\":" + "" + returnjson + "" + ",";
            jsonString = jsonString.TrimEnd(',');
            jsonString += "}";
            return jsonString;
        }
        public static string ListToJsonYHK<T>(IList<T> list, int start, int limit)
        {
            int shu = list.Count;
            int xunhuanshu = 0;
            List<T> returnlist = new List<T>();
            if (start + limit > shu)
            {
                xunhuanshu = shu;
            }
            else
            {
                xunhuanshu = start + limit;
            }
            for (int i = start; i < xunhuanshu; i++)
            {
                returnlist.Add(list[i]);
            }
            JsonSerializerSettings jsSettings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            string returnjson = JsonConvert.SerializeObject(returnlist, jsSettings);

            return returnjson;
        }

        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
        public static System.Data.DataTable ToDataTable<T>(this List<T> items)
        {
            var tb = new System.Data.DataTable(typeof(T).Name);
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                //Type t = typeof(string);
                //tb.Columns.Add(prop.Name, t);
                if (prop.Name == "ShouJiHaoMa")
                {
                    tb.Columns.Add(prop.Name, typeof(string));
                }
            }
            //foreach (T item in items)
            //{
            //    var values = new object[props.Length];
            //    for (int i = 0; i < props.Length; i++)
            //    {
            //        if (i == 6)
            //        {
            //            values[i] = props[i].GetValue(item, null);
            //        }
            //    }
            //    tb.Rows.Add(values);
            //}
            foreach (T item in items)
            {
                var values = new object[1];
                for (int i = 0; i < props.Length; i++)
                {
                    if (i == 6)
                    {
                        values[0] = props[i].GetValue(item, null);
                    }
                }
                tb.Rows.Add(values);
            }
            return tb;
        }
        public static System.Data.DataTable ToDataTable<T>(this List<T> items, List<int> list)
        {
            var tb = new System.Data.DataTable(typeof(T).Name);
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            for (int i = 0; i < props.Length; i++)
            {
                bool b = true;
                foreach (var item in list)
                {
                    if (i == item)
                    {
                        b = false;
                        break;
                    }
                }
                if (b)
                {
                    Type t = typeof(string);
                    tb.Columns.Add(props[i].Name, t);
                }
            }
            foreach (T item in items)
            {
                var values = new object[props.Length];
                for (int i = 0; i < props.Length; i++)
                {
                    bool b = true;
                    foreach (var item0 in list)
                    {
                        if (i == item0)
                        {
                            b = false;
                        }
                    }
                    if (b)
                    {
                        values[i] = props[i].GetValue(item, null);
                    }
                }
                tb.Rows.Add(values);
            }
            return tb;
        }
        public static Type GetCoreType(Type t)
        {
            if (t != null)
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }
        /// <summary>
        /// 将DataTable数据导入到excel中
        /// </summary>
        /// <param name="fileName">要导出的文件名</param>
        /// <param name="data">要导出的数据</param>
        /// <param name="sheetName">excel的sheet的名称</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <returns>导入数据行数(包含列名那一行)</returns>
        public static int DataTableToExcel(string fileName, System.Data.DataTable data, string sheetName, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;
            IWorkbook workbook = null;
            FileStream fs = null;
            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook();
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook();
            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);
                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                workbook.Write(fs); //写入到excel
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return -1;
            }
        }
    }
}
